package com.example.main;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

public class TopicProducer {
    /**
     * 生产者 → 消息队列
     * 创建连接工厂,并设置参数
     * 创建连接 Connection
     * 创建通道 Channel
     * ----------------
     * 创建交换机
     * 创建队列
     * 交换机绑定到队列
     * <p>
     * 发送消息
     */
    //定义交换机名称
    private static final String TOPIC_EXCHANGE_NAME = "my_topic_exchange";
    //定义一个 Q1 队列
    private static final String Q1_QUEUE_NAME = "q1";
    //定义一个 Q2 队列
    private static final String Q2_QUEUE_NAME = "q2";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        if (true) {
            factory.setHost("127.0.0.1");
            factory.setPort(5672);
            factory.setUsername("guest");
            factory.setPassword("guest");
            factory.setVirtualHost("/");
        }
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //创建交换机,使用路由模式的交换机
        channel.exchangeDeclare(TOPIC_EXCHANGE_NAME, BuiltinExchangeType.TOPIC, true, false, false, null);
        //创建队列
        channel.queueDeclare(Q1_QUEUE_NAME, true, false, false, null);
        channel.queueDeclare(Q2_QUEUE_NAME, true, false, false, null);

        //绑定交换机
        channel.queueBind(Q1_QUEUE_NAME, TOPIC_EXCHANGE_NAME, "*.orange.*");

        channel.queueBind(Q2_QUEUE_NAME, TOPIC_EXCHANGE_NAME, "*.*.rabbit");
        channel.queueBind(Q2_QUEUE_NAME, TOPIC_EXCHANGE_NAME, "lazy.#");

        //发送短信
        String[] msg = {
                "quicker.orange.rabbit",
                "lazy.orange.elephant",
                "quick.orange.fox",
                "lazy.brown.fox",
                "lazy.pink.rabbit",
                "quick.brown.fox",
                "orange",
                "quick.orange.male.rabbit",
                "lazy.orange.male.rabbit"
        };
        for (int i = 0; i < 30; i++) {
            int random = (int) (Math.random() * 9);   //生成0,1,2,4,5,6,7,8随机数
            String data = msg[random];

            String str = "我是 " + data + "\t消息\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS").format(new Date());
            System.out.println("发送消息:\t" + data);
            channel.basicPublish(TOPIC_EXCHANGE_NAME, data, null, str.getBytes());
        }

        // 关闭资源
        channel.close();
        connection.close();
    }
}
